class Solution {
public:
    struct kvCompare {
        bool operator()(const pair<string, int>& kv1, const pair<string, int>& kv2) {
            return kv1.second > kv2.second;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> coutMap;
        for (auto& e : words) {
            coutMap[e]++;
        }
        vector<pair<string, int>> kv(coutMap.begin(), coutMap.end());
        stable_sort(kv.begin(), kv.end(), kvCompare());
        vector<string> strV;
        for (int i = 0;i < k;i++) {
            strV.push_back(kv[i].first);
        }
        return strV;
    }
};